package luj.tool.jnproxyan.framework.lujnet.receive;

import io.netty.buffer.ByteBuf;
import luj.net.api.server.FrameDataReceiver;
import luj.tool.jnproxyan.framework.lujnet.ConnState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.nio.charset.StandardCharsets;

@Component
final class Recv44RequestAddrDomain implements FrameDataReceiver {

  @Override
  public Result receive(Context ctx) throws Exception {
    ByteBuf frameBuf = ctx.getLastFrame();
    ConnState connState = ctx.getConnectionState();

    byte[] domainBuf = new byte[connState.getDomainLen()];
    frameBuf.readBytes(domainBuf);

    String domain = new String(domainBuf, StandardCharsets.UTF_8);
    connState.setDstAddr(domain);
    LOG.debug("{}", InetAddress.getByName(domain));

    return ctx.then()
        .waitBytes(2)
        .nextReceiver(_receivePort);
  }

  private static final Logger LOG = LoggerFactory.getLogger(Recv44RequestAddrDomain.class);

  @Autowired
  private Recv45RequestPort _receivePort;
}
